/**create by liuhua at 2020年10月22日 下午5:32:22**/
package com.star.aries.dao;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.star.aries.domain.TrainType;
import com.star.aries.service.HnJson;
import com.star.aries.utils.FileUtils;

@Service
public class TrainTypeDao {
  private final String file = "traintype.star";
  private final String folder = "train_type/";
  
  @Autowired
  private HnJson hnJson;
  
  public List<TrainType> listTrainType() throws IOException {
    File f = new File(file);
    if(! f.exists()) {
      return new ArrayList<>();
    }
    String content = FileUtils.read(file);
    return hnJson.str2list(content, TrainType.class);
  }
  
  public void addTrainType(TrainType save) throws IOException {
    List<TrainType> all = listTrainType();
    Long prevId = all.stream().mapToLong(type -> type.getTrainTypeId()).max().orElse(0L);
    save.setTrainTypeId(prevId + 1);
    File f = new File(folder + save.getTrainTypeId());
    if(! f.exists()) {
      f.mkdirs();
    }
    save.setExcelPath(f.getAbsolutePath());
    all.add(save);
    FileUtils.save(file, hnJson.obj2string(all));
  }
  
  public TrainType getTrainType(Long trainTypeId) throws IOException {
    List<TrainType> all = listTrainType();
    return all.stream().filter(type -> type.getTrainTypeId().equals(trainTypeId)).findAny().orElse(null);
  }

  public List<TrainType> listTrainTypeByName(String name) throws IOException {
    List<TrainType> all = listTrainType();
    return all.stream().filter(type -> type.getName().equals(name)).collect(Collectors.toList());
  }

  public void updateTrainType(TrainType update) throws IOException {
    List<TrainType> all = listTrainType();
    all.removeIf(type -> type.getTrainTypeId().equals(update.getTrainTypeId()));
    File f = new File(update.getExcelPath());
    if(! f.exists()) {
      f.mkdirs();
    }
    update.setExcelPath(f.getAbsolutePath());
    all.add(update);
    FileUtils.save(file, hnJson.obj2string(all));
  }

  public void deleteTrainType(Long trainTypeId) throws IOException {
    List<TrainType> all = listTrainType();
    all.removeIf(type -> type.getTrainTypeId().equals(trainTypeId));
    FileUtils.save(file, hnJson.obj2string(all));
  }
}
